const jwt = require('jsonwebtoken');
const { User } = require('../models');

const { UnauthorizedError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');

module.exports = async (req, res, next) => {
    try {
        console.log('req==>',req)
        const { token } = req.headers;
        if (!token) {
            throw new UnauthorizedError("当前接口需要认证才能访问");
        }

        // 验证
        const decoded = jwt.verify(token, process.env.SECRET);
        console.log('decoded=>',decoded)
        const { userId } = decoded;

        // const user = await User.findByPk(userId);
        // if (!user) {
        //     throw new UnauthorizedError('用户不存在')
        // }

        // 如果通过验证，江userId挂在到req上，方便后续中间件或路由使用
        req.userId = userId;

        next();
    } catch (error) {
        failure(res,error)
    }
}
